package com.itestor.iptv.utils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.sql.Blob;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Hibernate;

/**
 * 系统辅助. 
 */
public class SystemHelper {

    /**
     * 
     */
    private static final Logger logger = Logger.getLogger(SystemHelper.class);

    /**
     * 生成按状态查询条件.
     * @param stateNames 状态名称
     * @return String
     */
    public static String generateStateQueryCondition(String[] stateNames) {

        StringBuilder queryCondition = new StringBuilder();

        queryCondition.append(" and (");
        String connector = "";
        for (String stateName : stateNames) {
            queryCondition.append(connector + "(w.stateName='" + stateName
                    + "')");
            connector = " or ";
        }
        queryCondition.append(") ");

        return queryCondition.toString();
    }

    /**
     * @param mapping mapping
     * @param navigateId navigateId
     * @param navigateAction navigateAction
     * @return ActionForward 跳转位置.
     */
    public static ActionForward getDetailForward(ActionMapping mapping,
            String navigateId, String navigateAction) {

        ActionForward forward = mapping.findForward("WorksheetDetail");

        StringBuffer parameter = new StringBuffer(forward.getPath());
        parameter.append("?navigate_id=");
        parameter.append(navigateId);

        if (!"".equals(navigateAction)) {
            parameter.append("&navigate_action=");
            parameter.append(navigateAction);
        }

        return new ActionForward(parameter.toString(), true);
    }
    
    /**
     * @param mapping mapping
     * @param navigateId navigateId
     * @return ActionForward 跳转位置.
     */
    public static ActionForward getDetailForward(ActionMapping mapping,
            String navigateId) {
        return getDetailForward(mapping, navigateId, "");
    }

    /**
     * @param request request
     * @param msg msg
     * @param bundle bundle
     */
    public static void addMessage(HttpServletRequest request, String msg,
            String bundle) {
        MessageCenter msgc = (MessageCenter) request.getSession().getAttribute(
                "MessageCenter");
        if (msgc == null) {
            msgc = new MessageCenter();
            request.getSession().setAttribute("MessageCenter", msgc);
        }
        Message message = new Message(msg, bundle);
        msgc.addMessage(message);
    }

    /**
     * 获取日期对象.
     * @return Date 日期对象
     */
    public static Date getDate() {
        return new Date();
    }

    /**
     * 获取一定时间段之后的时间.
     * @return Date 日期对象
     * @param minutes 分钟
     */
    public static Date addDate(long minutes) {
        long time = System.currentTimeMillis() + minutes * 60000;
        return new Date(time);
    }

    /**
     * 获取日期对象.
     * @param dateString 日期字符串
     * @return Date 日期对象
     */
    public static Date getDate(String dateString) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = dateFormat.parse(dateString);
        } catch (ParseException e) {            
            return null;
        }

        return date;
    }

    /**
     * 获取日期字符串.
     * @return Date 日期字符串
     */
    public static String formatDate() {
        return formatDate(new Date());
    }

    /**
     * 获取日期字符串.
     * @param date 日期对象
     * @return Date 日期字符串
     */
    public static String formatDate(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(date);
    }

    /**
     * 格式化日期对象.
     * @return Date 日期对象
     */
    public static String formatTime() {
        return formatTime(new Date());
    }

    /**
     * 格式化日期对象.
     * @param date 日期对象
     * @return String 经过格式化的日期字符串
     */
    public static String formatTime(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return dateFormat.format(date);
    }

    /**
     * 格式化日期对象.
     * @param date 日期对象
     * @return String 经过格式化的日期字符串
     */
    public static String formatDeTime(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date);
    }

    /**
     * 根据缩写返回相应的子网掩码.
     * @param netMask netMask
     * @return String netMask
     */
    public static String getNetMask(int netMask) {
        StringBuffer fullNetMask = new StringBuffer();
        String dot = "";
        int digits = netMask / 8;
        int remainder = netMask % 8;
        for (int i = 0; i < digits; i++) {
            fullNetMask.append(dot + "255");
            dot = ".";
        }
        fullNetMask.append(dot
                + (255 - (int) (Math.pow(2, (8 - remainder))) + 1));
        dot = ".";
        for (int i = 3; i > digits; i--) {
            fullNetMask.append(dot + "0");
        }
        return fullNetMask.toString();
    }

    /**
     * String 转换为Blob.
     * @param data data
     * @return Blob Blob
     */
    public static Blob convertToBlob(String data) {
        return Hibernate.createBlob(data.getBytes());
    }

    /**
     * byte[] 转换为Blob.
     * @param data data
     * @return Blob Blob
     */
    public static Blob convertToBlob(byte[] data) {
        return Hibernate.createBlob(data);
    }

    /**
     * Blob转换为String.
     * @param blob Blob
     * @return String String
     */
    public static String convertToString(Blob blob) {
        try {
            InputStream inputStream = blob.getBinaryStream();
            InputStreamReader in = new InputStreamReader(inputStream);

            StringWriter writer = new StringWriter();
            char[] buffer = new char[1024 * 4];

            int length = 0;
            while (-1 != (length = in.read(buffer))) {
                writer.write(buffer, 0, length);
            }
            in.close();

            return writer.toString();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return null;
    }

    /**
     * Blob转换为Byte[].
     * @param blob Blob
     * @return String String
     */
    public static byte[] convertToBytes(Blob blob) {
        try {
            return blob.getBytes(1, (int) blob.length());
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return null;
    }

    /**
     * 将数组用逗号连接成字符串.
     * @param arr String[].
     * @return String.
     */
    public static String joinArrayByComma(String[] arr) {
        String str = null;
        if (arr.length >= 1) {
            if (arr.length > 1) {
                str = arr[0] + ",";
            } else {
                str = arr[0];
            }
        }
        int temp;
        for (temp = 1; temp < arr.length - 1; temp++) {
            if (arr[temp] != null) {
                str = str + arr[temp] + ",";
            }
        }
        if (arr.length > 1) {
            str = str + arr[temp];
        }
        return str;
    }
}
